import axios from 'axios';
import { useMessage } from '@/hooks/message';
import appConfig from '@/config';

// eslint-disable-next-line react-hooks/rules-of-hooks
const { uesErrorMsg } = useMessage();
const service = axios.create({
  url: appConfig.baseApi,
  timeout: 80000,
});

/**
 * 请求拦截
 */
service.interceptors.request.use(
  (config) => {
    // Store 必须在拦截器内部导入，在外部导入会显示 Pinia 未初始化
    // 设置请求头部 Authorization
    // const token=localStorage.getItem("token")
    // if (token) {
    //   config.headers['Authorization'] = 'Bearer ' + token;
    // }
    const isMock = appConfig.mock;
    if (appConfig.env === 'prod') {
      // eslint-disable-next-line no-param-reassign
      config.url = appConfig.baseApi + config.url;
    } else {
      // eslint-disable-next-line no-param-reassign
      config.url = (isMock ? appConfig.mockApi : appConfig.baseApi) + config.url;
    }
    // eslint-disable-next-line no-param-reassign
    config.headers['Content-Type'] = 'application/json';
    return config;
  },
  (error) => {
    console.error(error);
    return Promise.reject(error);
  },
);

/**
 * 响应拦截
 */
service.interceptors.response.use(
  (response) => {
    const { code, message } = response.data;
    // 如果过期则退出登录
    if (code === 401) {
      uesErrorMsg('Token 已过期, 请重新登陆');
      window.location.href = '/login';
    }
    console.log(message);
    return response.data;
  },
  (error) => {
    Promise.reject(error);
  },
);

export default service;
